package jdk5.concurrent.tiger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class Logger extends Thread{
           private BlockingQueue<String> msgQueue;
           private PrintWriter logger = new PrintWriter(System.out);
           private boolean shutdown;

           public Logger(String logFileName, BlockingQueue<String> msgQueue) 
                 throws IOException{
                   if(logFileName != null) 
                            logger = new PrintWriter(new FileWriter(logFileName));
                   this.msgQueue = msgQueue;                   
            }

            public void run(){
                    while(!shutdown || !msgQueue.isEmpty()){
                            try{
                                  String msg = msgQueue.poll();
                                  if(msg != null) logger.println(msg);
                                  logger.flush();
                            }catch(Exception e){
                                 e.printStackTrace();
                           }
                     }
                     logger.close();
            }

           public void shutdown(){ shutdown = true; }

          public static void main(String[] args) throws Exception{
                  final BlockingQueue<String> msgQueue = 
                          new ArrayBlockingQueue<String>(10);      
                  Logger l = new Logger(null, msgQueue);
                  l.start();
                  for(int i = 0; i < 5; i++){
                          new Thread(){
                                 public void run(){
                                        for(int i = 0; i < 5; i++){
                                                  try{
                                                       msgQueue.put(Thread.currentThread().getName() 
                                                             + ": send mesg " + i);
                                                  }catch(Exception e){} 
                                       }
                                 }
                          }.start();
                  }
                  Thread.sleep(1000);
                  l.shutdown();
           }
}